import {Avatar, Button, message, Modal, Radio, Tag} from 'antd';
import React, {useEffect, useRef, useState} from 'react';
import {PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {OpCircleManager} from "@/services/api-functions";
import ProTable, {ActionType, ProColumns} from "@ant-design/pro-table";
import {history} from "@@/core/history";
import {ExclamationCircleOutlined} from "@ant-design/icons";

export const modifyCirclePostStatus = async (select: any, state: number) => {
  if (!select) return true;
  try {
    if (isSuccess((await OpCircleManager.dynamicStatusMod(state, select.id))?.code)) {
      message.success(1 === state ? '启用成功' : '禁用成功');
      return true;
    }
    return false
  } catch (error) {
    return false;
  }
};

const CirclePostList: React.FC<any> = ({location:{query: {circleId}}}) => {

  const actionRef = useRef<ActionType>();
  const [upState, setUpState] = useState<'all' | 'essence' | 'head_fixed'>('all');
  const [countInfo, setCountInfo] = useState<{ all: number, essence: number, head_fixed: number }>({
    all: 0,
    essence: 0,
    head_fixed: 0,
  });

  useEffect(() => {
    console.log(circleId)
    if(actionRef?.current){
      actionRef.current.reload()
    }

  }, [circleId])

  const columns: ProColumns[] = [
    {
      title: '选择圈子',
      dataIndex: 'circleName',
      hideInTable: true,
    },
    {
      title: '发布用户',
      dataIndex: 'nickName',
      hideInTable: true,
    },
    {
      title: '发布用户',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
      dataIndex: 'userDto',
      render: (_, record) => <><Avatar src={record?.userDto?.avatarUrl}/>&nbsp;<span>{record?.userDto?.nickName}</span></>,
    },
    {
      title: '动态内容',
      dataIndex: 'content',
      ellipsis: true,
      width: 200,
    },
    {
      title: '标签',
      dataIndex: 'label',
      hideInTable: true,
    },
    {
      title: '所属圈子',
      dataIndex: 'circleName',
      ellipsis: true,
      hideInSearch: true,
      width: 120,
    },
    {
      title: '是否同步至首页',
      dataIndex: 'homePage',
      hideInSearch: true,
      width: 120,
      render: (_, record) => record.homePage ? '是' : '否'
    },
    {
      title: '是否精选',
      dataIndex: 'essence',
      hideInSearch: true,
      width: 80,
      render: (_, record) => record.essence ? '是' : '否'
    },
    {
      title: '是否置顶',
      dataIndex: 'headFixed',
      hideInSearch: true,
      width: 80,
      render: (_, record) => record.headFixed ? '是' : '否'
    },
    {
      title: '浏览量',
      dataIndex: 'browseNum',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '点赞数',
      dataIndex: 'greatNum',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '收藏数',
      dataIndex: 'focusNum',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '评论',
      dataIndex: 'replyNum',
      hideInSearch: true,
      width: 100,
    },
    {
      title: '发布时间',
      dataIndex: 'gmtCreate',
      ellipsis: true,
      hideInSearch: true,
      width: 150,
    },
    {
      title: '发布时间',
      dataIndex: 'publishTimeRange',
      hideInTable: true,
      valueType: 'dateTimeRange',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInSearch: true,
      hideInForm: true,
      fixed: 'right',
      render: (_, record) => [
        <a key="edit" onClick={() => Modal.confirm({
          title: '提示',
          icon: <ExclamationCircleOutlined/>,
          content: <span>确定要删除 <Tag color='#108ee9'>{record.content}</Tag> 吗？</span>,
          okText: '删除',
          cancelText: '取消',
          onOk: async () => {
            if (await modifyCirclePostStatus(record, 0)) {
              actionRef.current?.reload()
            }
          },
        })}>删除</a>,
        record.enabling == '0'
          ? <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要启用 <Tag color='#108ee9'>{record.content}</Tag> 吗？</span>,
            okText: '启用',
            cancelText: '取消',
            onOk: async () => {
              if (await modifyCirclePostStatus(record, 0)) {
                actionRef.current?.reload()
              }
            },
          })}>启用</a>
          : <a key="edit" onClick={() => Modal.confirm({
            title: '提示',
            icon: <ExclamationCircleOutlined/>,
            content: <span>确定要禁用 <Tag color='#108ee9'>{record.content}</Tag> 吗？</span>,
            okText: '禁用',
            cancelText: '取消',
            onOk: async () => {
              if (await modifyCirclePostStatus(record, 1)) {
                actionRef.current?.reload()
              }
            },
          })}>禁用</a>,
        <a key="edit" href={`/circle/post/list/${record?.id}`}>详情</a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<any, any>
        actionRef={actionRef}
        rowKey="key"
        search={{labelWidth: 120,}}
        headerTitle={<Radio.Group value={upState} onChange={(e) => {
          setUpState(e.target.value)
          actionRef.current?.reload()
        }}>
          <Radio.Button value='all'>全部 {countInfo?.all ?? 0}</Radio.Button>
          <Radio.Button value='essence'>精选 {countInfo?.essence ?? 0}</Radio.Button>
          <Radio.Button value='head_fixed'>置顶 {countInfo?.head_fixed ?? 0}</Radio.Button>
        </Radio.Group>}
        toolBarRender={() => [
          <Button onClick={() => history.push('/circle/comment/list')}> 评论列表</Button>
        ]}
        request={async (params) => {

          const query = {...params}
          if (upState !== 'all') {
            query.page = upState
          }

          console.log(query)

          if(query.publishTimeRange){
            query.startTime = query.publishTimeRange[0]
            query.endTime = query.publishTimeRange[1]
            delete query.publishTimeRange
          }

          if(circleId){
            query.circleId = circleId
          }

          const {data: {data, total}, code}: any = await OpCircleManager.dynamicQuery(query);

          const res = await OpCircleManager.dynamicCountInfo();

          if(isSuccess(res.code)){
            setCountInfo(res.data)
          }

          return {data: data || [], success: isSuccess(code), total: isSuccess(code) ? total : 0};
        }}
        columns={columns}
        scroll={{ x: 1300 }}
      />
    </PageContainer>
  );
};

export default CirclePostList;
